<?php

namespace app\services;

use plugin\admin\app\model\User;
use plugin\admin\app\model\UserLevel;
use plugin\admin\app\model\UserLevelLog;
use plugin\admin\app\model\UserRecommendTeam;
use plugin\admin\app\model\UserTeam;

class UserLevelService
{
    public static function list()
    {
        return UserLevel::all()->toArray();
    }

    public static function levelUp($userId, $level, $remark = '')
    {
        $user = User::find($userId);

        if ($user->level < $level) {
            UserLevelLog::insert([
               'user_id' => $userId,
               'level' => $level,
                'created_time' => date('Y-m-d H:i:s'),
                'remark' => $remark
            ]);
            $user->level = $level;
            $user->save();
        }
    }

    /**
     * 伞下成员满足条件，升级
     *
     * @param $userId
     * @return int|void
     */
    public static function levelUpCheck($userId)
    {
        $teamInfo = UserTeam::where('user_id', $userId)->first();

        $userLevels = UserLevel::where('id', '>', 0)->get()->toArray();
        $userLevels = array_combine(
            array_column($userLevels, 'id'),
            array_values($userLevels)
        );

        if ($userLevels[7]['limit_count'] > 0 && $teamInfo['team_count'] >= $userLevels[7]['limit_count']) {
            return 7;
        }

        if ($userLevels[6]['limit_count'] > 0 && $teamInfo['level4_count'] >= $userLevels[6]['limit_count']) {
            return 6;
        }

        if ($userLevels[5]['limit_count'] > 0 && $teamInfo['level3_count'] >= $userLevels[5]['limit_count']) {
            return 5;
        }

        if ($userLevels[4]['limit_count'] > 0 && $teamInfo['level2_count'] >= $userLevels[4]['limit_count']) {
            return 4;
        }

        if ($userLevels[3]['limit_count'] > 0 && $teamInfo['recommend_count'] >= $userLevels[3]['limit_count'])  {
            return 3;
        }
    }

    /**
     * 两个月没有购买抱单礼包，等级状态设置为异常
     * 三个月没有购买抱单礼包，等级设置为社员
     *
     * @return void
     */
    public static function levelStatusCheck()
    {
        $levelUsers = User::where('level', '>', 1)->get()->toArray();

        foreach ($levelUsers as $levelUser) {
            $threeMonthCount = OrderService::getRangeTimeGiftOrderCount(date('Y-m-01', strtotime('-3 months')), date('Y-m-t', strtotime('-1 months')), $levelUser['id']);

            $twoMonthCount = OrderService::getRangeTimeGiftOrderCount(date('Y-m-01', strtotime('-3 months')), date('Y-m-t', strtotime('-1 months')), $levelUser['id']);

            if ($threeMonthCount == 0) {
                User::where('id', $levelUser['id'])->update(['level' => 1]);
            }

            if ($twoMonthCount == 0) {
                User::where('id', $levelUser['id'])->update(['level_status' => User::LEVEL_STATUS_EXCEPTION]);
            }
        }
    }
}